#!/bin/bash

# Get the last line of the version output
last_line=$(npm show node@20 version | tail -n 1)

# Extract the second token using awk and remove quotes
version=$(echo "$last_line" | awk '{print $2}' | tr -d "'")

if [ -z "$version" ]; then
    echo "Error: Could not extract version number" >&2
    exit 1
fi

# Update the nodejs line in .tool-versions file
# If nodejs line exists, replace it; if not, append it
if grep -q "^nodejs" .tool-versions; then
    sed -i '' "s/^nodejs.*$/nodejs $version/" .tool-versions
else
    echo "nodejs $version" >> .tool-versions
fi

# Install the Node.js version via asdf to ensure it's available
echo "Installing Node.js version $version via asdf..."
if asdf install nodejs "$version"; then
    echo "Successfully installed Node.js version $version"
else
    echo "Warning: Failed to install Node.js version $version via asdf" >&2
    echo "Continuing with package.json update..." >&2
fi

# Update the Node.js version in package.json's oclif update configuration
# Using node to update the JSON file correctly
node -e "
const fs = require('fs');
const path = 'packages/cli/package.json';
const pkg = JSON.parse(fs.readFileSync(path, 'utf8'));
pkg.oclif.update.node.version = '$version';
fs.writeFileSync(path, JSON.stringify(pkg, null, 2) + '\n');
"

echo "Updated nodejs version to $version in .tool-versions and package.json"
